import wx from "weixin-js-sdk";
// import { showToast, showToast } from 'vant';
import { showToast } from 'vant'

import { orderPay } from "@/api"
export default async function onPay() {
  return new Promise(async (resolve, reject) => {
    const { code, data } = await orderPay({ product_id: -1, pay_type: 9 });
    if (code === 1000) {
      const {
        appId,
        timeStamp: timestamp,
        nonceStr,
        signature,
        signType,
        paySign,
      } = data.pay_data;
      console.log({appId,
        timestamp,
        nonceStr,
        signature: signType}, '支付参数')
      wx.config({
        debug: false,
        appId,
        timestamp,
        nonceStr,
        signature: signType,
        jsApiList: ["chooseWXPay"],
      });
      wx.error(() => {
        console.log("支付错误")
        showToast("支付错误");
        reject("支付错误")
      });
      wx.ready(() => {
        wx.checkJsApi({
          jsApiList: ["chooseWXPay"],
          success: () => {
            wx.chooseWXPay({
              timestamp,
              nonceStr,
              package: data.pay_data.package,
              signType,
              paySign,
              success: () => {
                console.log("支付成功")
                showToast("支付成功");
                resolve(data.order_no)
              },
              cancel: () => {
              console.log("你还未完成支付，请重新支付~")
                reject()
                showToast("你还未完成支付，请重新支付~");
              },
    
              fail: () => {
              console.log("支付失败")
                reject()
                showToast("支付失败");
              },
            });
          },
          fail: () => {
            console.log("取消支付")
            showToast("取消支付");
            reject()
          },
        });
      });
    } else {
      reject()
    }
  })
}